<template>
  <div class="audio-waveform-container">
    <!-- 波形显示区域 -->
    <div ref="waveform" class="waveform"></div>

    <!-- 控制按钮区域 -->
    <div class="controls">
      <input
        type="file"
        accept="audio/*"
        @change="handleFileSelect"
        class="file-input"
      />

      <button @click="togglePlay" :disabled="!isReady" class="control-btn">
        <i :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'"></i>
        {{ isPlaying ? "暂停" : "播放" }}
      </button>

      <button
        @click="stop"
        :disabled="!isReady || !isPlaying"
        class="control-btn"
      >
        <i class="fas fa-stop"></i> 停止
      </button>

      <div class="time-display" v-if="isReady">
        {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import WaveSurfer from "wavesurfer.js";

// 波形容器引用
const waveform = ref(null);

// 状态变量
const wavesurfer = ref(null);
const isReady = ref(false);
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const audioFile = ref(null);

// 初始化波形
onMounted(() => {
  // 创建wavesurfer实例
  wavesurfer.value = WaveSurfer.create({
    container: waveform.value,
    waveColor: "#4F46E5", // 波形颜色
    progressColor: "#818CF8", // 已播放部分颜色
    cursorColor: "#FFFFFF", // 光标颜色
    barWidth: 2, // 波形柱宽度
    barRadius: 3, // 波形柱圆角
    height: 120, // 高度
    barGap: 3, // 波形柱间距
    responsive: true, // 响应式
    normalize: true, // 归一化波形
    partialRender: true, // 部分渲染优化
  });

  // 事件监听
  wavesurfer.value.on("ready", () => {
    isReady.value = true;
    duration.value = wavesurfer.value.getDuration();
  });

  wavesurfer.value.on("audioprocess", () => {
    currentTime.value = wavesurfer.value.getCurrentTime();
  });

  wavesurfer.value.on("finish", () => {
    isPlaying.value = false;
  });

  wavesurfer.value.on("error", (err) => {
    console.error("WaveSurfer错误:", err);
    alert("加载音频失败: " + err);
  });
});

// 清理资源
onUnmounted(() => {
  if (wavesurfer.value) {
    wavesurfer.value.destroy();
  }
});

// 监听音频文件变化
watch(audioFile, (newFile) => {
  if (newFile) {
    loadAudioFile(newFile);
  }
});

// 加载音频文件
const loadAudioFile = (file) => {
  if (wavesurfer.value) {
    // 停止当前播放并清空
    wavesurfer.value.stop();
    isPlaying.value = false;

    // 创建文件URL并加载
    const audioUrl = URL.createObjectURL(file);
    wavesurfer.value.load(audioUrl);
  }
};

// 处理文件选择
const handleFileSelect = (e) => {
  const file = e.target.files[0];
  if (file && file.type.startsWith("audio/")) {
    audioFile.value = file;
    // 重置文件输入，允许重复选择同一文件
    e.target.value = "";
  } else {
    alert("请选择音频文件");
  }
};

// 播放/暂停切换
const togglePlay = () => {
  if (wavesurfer.value) {
    wavesurfer.value.playPause();
    isPlaying.value = !isPlaying.value;
  }
};

// 停止播放
const stop = () => {
  if (wavesurfer.value) {
    wavesurfer.value.stop();
    isPlaying.value = false;
  }
};

// 格式化时间（秒 -> MM:SS）
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, "0")}:${secs
    .toString()
    .padStart(2, "0")}`;
};
</script>

<style scoped>
.audio-waveform-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background-color: #1e1b4b;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.waveform {
  width: 100%;
  background-color: #2e2b5f;
  border-radius: 6px;
  margin-bottom: 15px;
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
}

.controls {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.file-input {
  padding: 8px;
  border-radius: 4px;
  border: none;
  background-color: #4338ca;
  color: white;
  cursor: pointer;
}

.file-input::-webkit-file-upload-button {
  background: #6366f1;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  color: white;
  cursor: pointer;
}

.control-btn {
  background-color: #6366f1;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  transition: background-color 0.2s;
}

.control-btn:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.control-btn:not(:disabled):hover {
  background-color: #818cf8;
}

.time-display {
  margin-left: auto;
  color: #e0e7ff;
  font-family: monospace;
}
</style>
